package com.meisupic.copyright.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.meisupic.copyright.domain.bo.SysUser;
import com.meisupic.copyright.domain.po.Users;
import com.meisupic.copyright.repo.UsersRepo;
import com.meisupic.copyright.support.HttpClient;
import com.meisupic.copyright.support.Response;
import com.meisupic.copyright.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Author lanjian
 * @Date 2018/4/14 下午8:56
 */
@Service("huabanLoginService")
public class HuabanLoginServiceImpl implements UserDetailsService {

  @Autowired
  UsersRepo usersRepo;

  private Logger logger = LoggerFactory.getLogger(this.getClass());

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Users users = getHubanUserInfo(username);
    if (users == null) {
      return null;
    }
    Users findUsers = usersRepo.findUsersByHuabanUserIdIs(users.getHuabanUserId());
    if (StringUtil.isEmpty(findUsers)) {
      findUsers = usersRepo.save(users);
    }
    SysUser sysUser = new SysUser();
    sysUser.setUserName(findUsers.getUserName());
    sysUser.setId(findUsers.getId());
    return sysUser;
  }

  private Users getHubanUserInfo(String sid) {
    JSONObject param = new JSONObject();
    param.put("sid", sid);
    Response response = HttpClient.post("http://121.52.226.218:3456/users/sid", param.toString(),null);
    if (response.getStatusCode() == 200) {
      String result = response.getContent();
      JSONObject object = JSON.parseObject(result);
      JSONObject user = object.getJSONObject("user");
      if(user==null){
        return null;
      }
      String email = user.getString("email");
      String tel = user.getString("tel");
      Long userId = user.getLong("user_id");
      Users users = new Users();
      users.setUserName(String.valueOf(userId));
      users.setHuabanUserId(userId);
      users.setMobile(tel);
      users.setEmail(email);
      return users;
    }
    logger.error("获取美素用户信息异常{}错误信息{}", response.getStatusCode(), response.getContent());
    return null;
  }
}
